package controller

import (
	"context"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"time"
	"user_bff/model/redis"
	"user_bff/pkg"
	"user_bff/user"
)

// 用户登录
func UserLogin(c *gin.Context) {
	mobile := c.PostForm("mobile")
	code := c.PostForm("code")
	if mobile == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "手机号不能为空",
			"data": nil,
		})
		return
	}
	if code == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "验证码不能为空",
			"data": nil,
		})
		return
	}
	//远程连接user_rpc
	client := pkg.Comment()
	resp, err := client.UserLogin(context.Background(), &user.UserLoginRequest{Mobile: mobile})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "查询用户信息失败",
			"data": nil,
		})
		return
	}
	//redis获取验证码
	sms, err := redis.GetSendSms(mobile)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "获取短信验证码失败",
			"data": nil,
		})
		return
	}
	//判断验证码是否正确
	if code != sms {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "短信验证码失败",
			"data": nil,
		})
		return
	}
	token, err := pkg.SetJwtToken(time.Now().Unix(), strconv.FormatInt(resp.Id, 10))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": -1,
			"msg":  "生成token失败",
			"data": resp.Id,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "登录成功",
		"data": token,
	})
	return
}
